import {
    showToast
} from "../../utils/asyncWx.js"
// pages/collect/collect.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabs: [{
                id: 0,
                value: "商品收藏",
                isActive: true
            },
            {
                id: 1,
                value: "历史足迹",
                isActive: false
            },
        ],
        colAndHis: [],
        manage: false,
        checkGoods: [],
        allChecked: false,
        goodsChecked: false,
        first: true
    },
    QueryParams: {
        pagenum: 1,
        pageSizes: 8
    },
    // 总页数
    totalPages: 1,
    Goods: [],
    onShow: function () {
        // 判断token是否存在 不存在跳转授权获取
        const token = wx.getStorageSync('token');
        if (!token) {
            wx.navigateTo({
                url: '/pages/auth/auth',
            });
            return;
        }
        let index = 0;
        if (this.data.first) {
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            index = currentPage.options.index;
            this.setData({first:false});
        } else {
            index = this.data.tabs.findIndex(v=>v.isActive);
        }
        this.changeTileByIndex(index);
        this.getColAndHis(index);
    },
    // 管理按钮
    handleManage() {
        let manage = !this.data.manage;
        this.setData({
            manage
        });
    },
    // 点击全选触发事件
    handleAllChange() {
        let allChecked = !this.data.allChecked;
        let goodsChecked = allChecked;
        let checkGoods = [];
        const collect = this.data.colAndHis;
        if (allChecked) {
            collect.forEach(v => checkGoods.push(v.goods_id));
        }
        this.setData({
            allChecked,
            checkGoods,
            goodsChecked
        });
    },
    // 点击单选框触发的事件
    handleItemChange(e) {
        const {
            id
        } = e.target.dataset;
        let {
            checkGoods,
            colAndHis,
            allChecked
        } = this.data;
        const i = checkGoods.findIndex(v => v === id);
        if (i === -1) {
            checkGoods.push(id);
        } else {
            checkGoods.splice(i, 1);
        }
        allChecked = colAndHis.length === checkGoods.length ? true : false;
        this.setData({
            checkGoods,
            allChecked
        });
    },
    // 根据标题索引激活选中标题数组
    changeTileByIndex(index) {
        // 修改原数组 isActive 变为 true
        let {
            tabs
        } = this.data
        tabs.forEach((v, i) => i == index ? v.isActive = true : v.isActive = false);
        // 赋值
        this.setData({
            tabs,
            colAndHis: [],
            allChecked: false,
            goodsChecked: false
        });
        // 切换列表
        this.getColAndHis(index);
    },
    //监听子组件触发的回调函数
    handleTabsItemChange(e) {
        // 获取被点击的标题索引
        const {
            index
        } = e.detail
        this.changeTileByIndex(index);
        // 重新发送请求
        this.getColAndHis(index);
    },
    getColAndHis(index) {
        if (index == 0) {
            this.Goods = wx.getStorageSync('collect') || [];
        } else if (index == 1) {
            this.Goods = wx.getStorageSync('history') || [];
        }
        const totalP = Math.ceil(this.Goods.length / this.QueryParams.pageSizes);
        if (this.totalPages < totalP) {
            this.totalPages = totalP;
        }
        this.setData({
            colAndHis: []
        });
        this.getGoodsList();
    },
    // 获取列表
    async getGoodsList() {
        let goods = this.Goods;
        // 分页设置
        const start = (this.QueryParams.pagenum - 1) * this.QueryParams.pageSizes;
        let end = start + this.QueryParams.pageSizes;
        // 越界判断
        if (end >= goods.length) end = goods.length;
        let choosenGoods = [];
        for (let i = start; i < end; i++) {
            choosenGoods.push(goods[i]);
        }
        const colAndHis = [...this.data.colAndHis, ...choosenGoods];
        this.setData({
            colAndHis
        });
    },
    // 删除操作
    async handleDelete() {
        let {
            checkGoods,
            allChecked,
            colAndHis,
            tabs
        } = this.data;
        if (!checkGoods.length) {
            await showToast({
                title: '请选择商品',
                icon: 'error',
                mask: true
            });
            return;
        }
        wx.showModal({
            title: '删除商品',
            content: '您确定要删除选中商品吗？',
            success: (res) => {
                if (res.confirm) {
                    if (allChecked) {
                        colAndHis = [];
                    } else {
                        checkGoods.forEach(v => colAndHis = colAndHis.filter(i => i.goods_id != v))
                    }
                    this.setData({
                        colAndHis,
                        checkGoods: [],
                        allChecked: false
                    });
                    if (tabs[0].isActive) {
                        wx.setStorageSync('collect', colAndHis);
                    } else {
                        wx.setStorageSync('history', colAndHis);
                    }
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        mask: true
                    });
                }
            }
        });

    },
    // 添加购物车操作
    async handleAddCart() {
        let cart = wx.getStorageSync('cart') || [];
        let {
            checkGoods,
            colAndHis,
            tabs
        } = this.data;
        if (!checkGoods.length) {
            await showToast({
                title: '请选择商品',
                icon: 'error',
                mask: true
            });
            return;
        }
        wx.showModal({
            title: '添加到购物车',
            content: '您确定要将选中商品添加到购物车吗？',
            success: (res) => {
                if (res.confirm) {
                    let goods = [];
                    checkGoods.forEach(v => {
                        cart = cart.filter(i => i.goods_id != v);
                        goods.push(...colAndHis.filter(i => i.goods_id == v));
                        colAndHis = colAndHis.filter(i => i.goods_id != v);
                    });
                    cart = [...goods, ...cart];
                    this.setData({
                        colAndHis,
                        checkGoods: [],
                        allChecked: false
                    });
                    if (tabs[0].isActive) {
                        wx.setStorageSync('collect', colAndHis);
                    } else {
                        wx.setStorageSync('history', colAndHis);
                    }
                    wx.setStorageSync('cart', cart);
                    wx.showToast({
                        title: '添加成功',
                        icon: 'success',
                        mask: true
                    });
                }
            }
        });
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        // 触发下拉刷新页面
        // 重置页码
        // 重置数组
        // 重新发送请求
        wx.showLoading({
            title: '正在加载...',
        });
        // 关闭下拉刷新窗口
        setTimeout(() => {
            this.QueryParams.pagenum = 1
            this.setData({
                colAndHis: []
            });
            this.getGoodsList();
            wx.hideLoading({
                success: (res) => {
                    wx.stopPullDownRefresh();
                },
            });
        }, 300)

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        // 判断还有没有下一页数据
        if (this.QueryParams.pagenum >= this.totalPages) {
            //无下一页数据
            wx.showToast({
                title: '已经到底啦~',
                mask: true
            });
        } else {
            // 添加0.3s加载提示模拟请求
            wx.showLoading({
                title: '正在加载...',
                mask: true
            });
            setTimeout(() => {
                this.QueryParams.pagenum++;
                this.getGoodsList();
                wx.hideLoading();
            }, 300);
        }
    },
})